from lib.utils import getEuclideanDistance, getFilenameByNumber
import json

import os

def mySort(arr):
    lens = len(arr)
    for i in range(lens - 1):
        for j in range(i + 1, lens):
            if arr[i]['distance'] > arr[j]['distance']:
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
    return arr


def findSimilaritySortList(category, baseFileIndex):
    if not os.path.exists('data/' + category + '.json'):
        return 0, category + '的数据还没有训练，请先训练', [], [], []
    with open('data/' + category + '.json', 'r') as f:
        data = json.loads(f.read())
        lens = len(data['color'])
        colorRes = []
        shapeRes = []
        textureRes = []
        baseFileIndex = baseFileIndex - 1
        for i in range(lens):
            if i != baseFileIndex:
                colorRes.append({'distance': getEuclideanDistance(data['color'][i], data['color'][baseFileIndex]), 'url': category + '/' + getFilenameByNumber(i + 1)})
                shapeRes.append({'distance': getEuclideanDistance(data['shape'][i], data['shape'][baseFileIndex]), 'url': category + '/' + getFilenameByNumber(i + 1)})
                textureRes.append({'distance': getEuclideanDistance(data['texture'][i], data['texture'][baseFileIndex]), 'url': category + '/' + getFilenameByNumber(i + 1)})
        return 1, '', mySort(colorRes), mySort(shapeRes), mySort(textureRes)
